package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;



import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    private UserMapper userMapper ;
    @Transactional
    @Override
    public String findUserByUP(User user) {
        byte [] bytes = user.getPassword().getBytes();
        String md5pass = DigestUtils.md5DigestAsHex(bytes);
        System.out.println(md5pass);
        user.setPassword(md5pass);
        User userDB = userMapper.findUserByUP(user);
        if(userDB == null ){//查询没有数据.返回null
            return null ;
        }
        return UUID.randomUUID().toString().replace("-", "");
    }
    @Transactional
    @Override
    public PageResult getUserListByPage(PageResult pageResult) {
        long total = userMapper.findTotal();
        int size = pageResult.getPageSize();
        int start = (pageResult.getPageNum()-1)*size;
       String query = pageResult.getQuery();
        List<User> userList = userMapper.finduserlistbypage(start,size,query);
        return pageResult.setTotal(total).setRows(userList);
//      long total = userMapper.findTotal();    //获取所有用户有几个
//      int size = pageResult.getPageSize();             //条数
//      int start = (pageResult.getPageNum()-1) * size ; //起始位置
//      //（页数减一）*条数
//      String query = pageResult.getQuery();            //查询条件
//      List<User> userList = userMapper.finduserlistbypage(start,size,query);
//       return pageResult.setTotal(total).setRows(userList);
    }
    @Transactional
    @Override
    public void updata(User user) {
        userMapper.update(user);
        System.out.println("更新状态完成");
    }

    @Transactional
    @Override
    public void saveUser(User user) {
        String password = user.getPassword();
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5).setStatus(true);
        //获取当前时间
       Date date = new Date();
        userMapper.saveUser(user);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findId(id);
    }
    @Transactional
    @Override
    public void updateUser(User user) {
        String phone = user.getPhone();
        String email = user.getEmail();
        user.setPhone(phone).setEmail(email);
         userMapper.updateUser(user);
    }

    @Transactional//(noRollbackFor = RuntimeException.class)
    @Override
    public void findDelete(Integer id) {
        userMapper.findDelete(id);
    }

    @Override
    public void findByIds(Integer userId) {
        userMapper.findIds(userId);
    }
}

